package com.the8thfold.anton.ant

import grails.plugins.springsecurity.Secured
import com.the8thfold.anton.users.User
import com.the8thfold.anton.utils.QuickId
import com.the8thfold.anton.users.UserRole
import com.the8thfold.anton.users.Role
import com.the8thfold.anton.users.Roles
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils


class AccountController {

    def springSecurityService

    //@Secured(['ROLE_ADMIN'])
    def index = {
        //redirect(action: "list", params: params)
        if (params.id && springSecurityService.isLoggedIn()){
            if (params.id.equals(springSecurityService.principal.userId)) {
                User user = User.findByUserId(params.id)

                //account.authorities.contains(Role.findByAuthority(Roles.ROLE_ADMIN.toString())) ? "checked" : ""
                def roles = [:]
                user.authorities.each {
                    roles.put(Roles.valueOf(it.authority), "checked")
                }
                [account: user, roles: roles]
            } else {
                redirect(controller: 'login',action: 'denied', params: params)
            }
        } else {
            redirect(action: 'list', params: params)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def list = {
        [accounts: User.findAll()]
    }

    @Secured(['ROLE_ADMIN'])
    def create = {

    }

    @Secured(['ROLE_ADMIN'])
    def save = {
        User user = new User()
        user.userTenantId = 1
        user.userId = QuickId.newId
        user.username = params.userName
        user.emailAddress = params.emailAddress
        user.firstName = params.firstName
        user.lastName = params.lastName
        user.password = springSecurityService.encodePassword(params.password)
        user.enabled = true

        user.save(flush: true, failOnError: true)

        [params.c1].flatten().each {
            UserRole.create user,Role.findByAuthority(it), true
        }

        redirect(action: 'list')
    }

    @Secured(['ROLE_ADMIN'])
    def view = {
        if (params.id){
            User user = User.findByUserId(params.id)
            //account.authorities.contains(Role.findByAuthority(Roles.ROLE_ADMIN.toString())) ? "checked" : ""
            def roles = [:]
            user.authorities.each {
                roles.put(Roles.valueOf(it.authority), "checked")
            }
            [account: user, roles: roles]
        } else {
            redirect(action: 'list', params: params)
        }
    }

    def account = {

    }

    @Secured(['ROLE_ADMIN'])
    def delete = {
        if (params.id){
            User user = User.findByUserId(params.id)
            if (user){
                user.delete(flush: true, failOnError: true)
            }
        }
        if (params.origin){
            redirect(url: params.origin.decodeURL(), params: params)
        } else {
            redirect(action: 'list', params: params)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def updateRole = {
        if (params.id) {
            User user = User.findByUserId(params.id)
            if (user){
                def roles = UserRole.findAllByUser(user)
                roles.each { it.delete(flush: true, failOnError: true)}

                [params.c1].flatten().each {
                    UserRole.create user,Role.findByAuthority(it), true
                }
            }
            redirect(action: 'view', params: params)
        } else {
            redirect(action: 'list', params: params)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def updateField = {
        if (params.id ) {
            User user = User.findByUserId(params.id)
            user.properties.put(params.field,params.value)
            user.save(flush:true, failOnError: true)
        }
        render("")
    }

    def updateFieldSelf = {
        if (params.id && springSecurityService.isLoggedIn()) {
            if (params.id.equals(springSecurityService.principal.userId)){
                User user = User.findByUserId(params.id)
                user.properties.put(params.field,params.value)
                user.save(flush:true, failOnError: true)
            } else {
                redirect(controller: 'login', action: 'denied', params: params)
            }
        }
        render("")
    }

    @Secured(['ROLE_ADMIN'])
    def updateScriptsAndJobs = {
        if (params.id) {
            User user = User.findByUserId(params.id)
            if (user){
                def scripts = AntScriptUser.findAllByUser(user)
                scripts.each { it.delete(flush: true, failOnError: true)}

                def jobs = AntJobUser.findAllByUser(user)
                jobs.each { it.delete(flush: true, failOnError: true)}

                if (params.scripts) {
                    [params.scripts].flatten().each {
                        AntScript script = AntScript.findByScriptId(it)
                        script.addToUsers(new AntScriptUser(user: user, script: script))
                    }
                }

                if (params.jobs) {
                    [params.jobs].flatten().each {
                        AntJob job = AntJob.findByJobId(it)
                        job.addToUsers(new AntJobUser(user: user, job: job))
                    }
                }
            }
            render("")
        } else {
            render("")
        }
    }

    def changePasswordSelf = {
        if (request.method == "POST") {
            if (springSecurityService.isLoggedIn()) {
                if (params.id.equals(springSecurityService.principal.userId)) {
                    User user = User.findByUserId(springSecurityService.principal.userId)
                    def old = springSecurityService.encodePassword(params.old)
                    def new1 = springSecurityService.encodePassword(params.new1)
                    def new2 = springSecurityService.encodePassword(params.new2)
                    if (old.equals(user.password)) {
                        if (new1.equals(new2)){
                            user.password = new1
                            user.save(flush: true, failOnError: true)
                            springSecurityService.reauthenticate(user.username, new1)
                            render("")
                        } else {
                            render("Passwords don't match")
                        }
                    } else {
                        render("Wrong password")
                    }
                } else {
                    render("Wrong user credentials")
                }
            } else {
                render("Failed to change password")
            }
        } else {
            render(template: 'changePasswordSelf', model: [id: params.id])
        }
    }

    @Secured(['ROLE_ADMIN'])
    def changePassword = {
        if (request.method == "POST") {
            User user = User.findByUserId(params.id)
            def new1 = springSecurityService.encodePassword(params.new1)
            def new2 = springSecurityService.encodePassword(params.new2)

            if (new1.equals(new2)){
                user.password = new1
                user.save(flush: true, failOnError: true)
                render("")
            } else {
                render("Passwords don't match")
            }

        } else {
            render(template: 'changePassword', model: [id: params.id])
        }
    }

    @Secured(['ROLE_ADMIN'])
    def disable = {
        if (params.id){
            User user = User.findByUserId(params.id)
            user.enabled = false;
            user.save(flush: true, failOnError: true)
        }
        redirect(url: params.origin.decodeURL())
    }

    @Secured(['ROLE_ADMIN'])
    def enable = {
        if (params.id){
            User user = User.findByUserId(params.id)
            user.enabled = true;
            user.save(flush: true, failOnError: true)
        }
        redirect(url: params.origin.decodeURL())
    }
}
